//
//  oldCenterSoundsBtnView.m
//  laonianbang
//
//  Created by 勇拓 李 on 18/3/10.
//  Copyright © 2018年 zaiyou. All rights reserved.
//

#import "oldCenterSoundsBtnView.h"
#import <AVFoundation/AVFoundation.h>
#import "oldHub.h"
#import "oldVoiceManager.h"
#import "RecordPlayerView.h"
#import "WarningPlayerView.h"

#define LIMIT_TIME 30.f

@interface oldCenterSoundsBtnView()<AVAudioRecorderDelegate>
@property (weak, nonatomic) IBOutlet UIButton *btn_start;
@property (weak, nonatomic) IBOutlet UILabel *label_notice;

@property (nonatomic, strong)RecordPlayerView *recordplayerView;

@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic,strong) AVAudioRecorder *audioRecorder;//音频录音机
@property (nonatomic, assign)float recordtime;//记录录音时长
@property (nonatomic, assign) BOOL isTurnOn;
@end

@implementation oldCenterSoundsBtnView

- (void)awakeFromNib
{
    [super awakeFromNib];
    [_btn_start addTarget:self action:@selector(goto_record:) forControlEvents:UIControlEventTouchDown];
    
    [_btn_start addTarget:self action:@selector(stopClick:) forControlEvents:UIControlEventTouchUpInside];
    
    _label_notice.text = @"按住说话";
}

- (void)removeFromParentView
{
    if (self.superview) {
        [self closetimer];
        [self removeFromSuperview];
        [self.layer removeAllAnimations];
    }
}

- (void)startTimer
{
    self.timer = [NSTimer timerWithTimeInterval:.5 target:self selector:@selector(timerBegin) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}

- (void)closetimer
{
    if (_timer) {
        if ([_timer isValid]) {
            [_timer invalidate];
        }
        _timer = nil;
    }
}

- (void)timerBegin
{
    _recordtime -= 0.5;
    if (_recordtime == 0) {
        [self stopClick:nil];
    }
}

#pragma mark - click
- (void)goto_record:(id)sender
{
    _label_notice.text = @"松开结束";
    _isTurnOn = !_isTurnOn;
    
    [self recordClick];
    [self startTimer];
    [self startRecordView];
    [self.delegate oldCenterSoundsBtnClick:YES error:NO];
}

- (void)stopClick:(id)sender
{
    _label_notice.text = @"按住说话";
    [self closetimer];
    [self removeRecordView];
    [self.delegate oldCenterSoundsBtnClick:NO error:[self stopRecord:sender]];
}

#pragma mark - RecordView
- (void)startRecordView
{
    _recordplayerView = [[[NSBundle mainBundle] loadNibNamed:@"RecordPlayerView"
                                                       owner:self
                                                     options:nil] objectAtIndex:0];
    _recordplayerView.audioRecorder = _audioRecorder;
    
    [_recordplayerView startRecord];
}

- (void)removeRecordView
{
    [_recordplayerView stopRecord];
}

#pragma mark - WarningView
- (void)warningByType:(NSInteger)type
{
    WarningPlayerView *warningplayerView = [[[NSBundle mainBundle] loadNibNamed:@"WarningPlayerView"
                                                                         owner:self
                                                                       options:nil] objectAtIndex:0];
    
    [warningplayerView soundsAlert:type];
}

#pragma mark record
/**
 *  获得录音机对象
 *
 *  @return 录音机对象
 */
-(AVAudioRecorder *)audioRecorder{
    if (!_audioRecorder) {
        //创建录音文件保存路径
        NSURL *url =  [NSURL URLWithString:[oldVoice getSavePath]];
        //创建录音格式设置
        NSDictionary *setting = [self getAudioSetting];
        //创建录音机
        NSError *error=nil;
        _audioRecorder=[[AVAudioRecorder alloc]initWithURL:url settings:setting error:&error];
        _audioRecorder.delegate = self;
        _audioRecorder.meteringEnabled=YES;//如果要监控声波则必须设置为YES
        if (error) {
            NSLog(@"创建录音机对象时发生错误，错误信息：%@",error.localizedDescription);
            return nil;
        }
    }
    return _audioRecorder;
}

/**
 *  取得录音文件设置
 *
 *  @return 录音设置
 */
-(NSDictionary *)getAudioSetting{
    NSMutableDictionary *dicM = [NSMutableDictionary dictionary];
    //设置录音格式
    //    [dicM setObject:@(kAudioFormatLinearPCM) forKey:AVFormatIDKey];
    //    [dicM setObject:@(kAudioFormatMPEG4AAC) forKey:AVFormatIDKey];
    //    //每个采样点位数,分为8、16、24、32
    //    [dicM setObject:@(YES) forKey:AVLinearPCMIsFloatKey];
    //....其他设置等
    
    [dicM setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];//
    
    //设置录音采样率，8000是电话采样率，对于一般录音已经够了
    [dicM setObject:@(8000) forKey:AVSampleRateKey];
    //设置通道,这里采用单声道
    [dicM setObject:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
    
    [dicM setObject:@(16) forKey:AVLinearPCMBitDepthKey];
    //是否使用浮点数采样
    [dicM setValue:[NSNumber numberWithInt:AVAudioQualityMin] forKey:AVEncoderAudioQualityKey];//音频质量
    
    return dicM;
}

- (void)recordClick{
    
    //    if (SIMULATOR) {
    //        [Utils warningUser:self msg:@"请使用真机测试录音！"];
    //        return;
    //    }
    
    WeakSelf
    
    [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
        if (granted) {
            [weakSelf audioRecorder];
            
            if(!_audioRecorder)
            {
                return;
            }
            
            [weakSelf DelayRecord];
            
        } else {
            [oldHub warningUser:@"请开启麦克风权限！"];
        }
    }];
}

- (void)DelayRecord
{
    if (_isTurnOn == NO) {
        return;
    }
    
    
    if (![self.audioRecorder isRecording]) {
        
        [self setAudioSession];
        [self.audioRecorder record];//首次使用应用时如果调用record方法会询问用户是否允许使用麦克风
    }
    
    [self initRecordTimer];
}

/**
 *  设置音频会话
 */
-(void)setAudioSession{
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    //设置为播放和录音状态，以便可以在录制完之后播放录音
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    
    [audioSession setActive:YES error:nil];
}

- (void)initRecordTimer
{
    _recordtime = LIMIT_TIME;
}

- (BOOL)stopRecord:(id)sender
{
    if (!_audioRecorder) {
        return YES;
    }
    
    _recordtime = _audioRecorder.currentTime;
    
    AVAudioSession *audioSession=[AVAudioSession sharedInstance];
    NSError *err = nil;
    [audioSession setCategory :AVAudioSessionCategoryPlayback error:&err];
    
    [self.audioRecorder stop];
    
    if(_recordtime > 2)
    {
        [self saveVoice];
        if (sender == nil) {
            [self warningByType:TIME_TOO_LONG];
        }
        
        return NO;
    }
    else
    {
        [self warningByType:TIME_TOO_SHORT];
        return YES;
    }
}

- (void)saveVoice
{
    
}

#pragma mark - 录音机代理方法
/**
 *  录音完成，录音完成后播放录音
 *
 *  @param recorder 录音机对象
 *  @param flag     是否成功
 */
-(void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{
    NSLog(@"录音完成!");
    if (_recordtime > 1) {
        
    }
    else
    {
        [recorder deleteRecording];
    }
}


@end
